
import { ElMessage } from "element-plus";

interface MyOptions extends Omit<RequestInit,"body">{
    body?:Record<string,any>
}


const baseUrl = "http://jacklv.cn"
export default function request(url:string,options:MyOptions={}):Promise<any>{
        const {body,...rest}=options
        let fetchOptions:RequestInit={
            ...rest
        }


    if(options.method && options.method.toLowerCase() !== 'get'){//非get请求
        fetchOptions.body = JSON.stringify(options.body || {});
        fetchOptions.headers = {
            "Content-Type":"application/json",
            
        }
    }
    fetchOptions.headers = {
        ...(fetchOptions.headers || {}),
        token:localStorage.token,
    }

    return fetch(baseUrl + url,fetchOptions)
    .then(response=> {
        switch(response.status){
            case 200:
                return response.json()
                case 401:
                    localStorage.clear()
                    window.location.hash=("#/login")
                    return Promise.reject("状态码非200或者401")
                    default:Promise.reject('状态码非200或者401')
        }
            

    }) 
    .then(res=>{
        if(res.code === 1){
            return res.data;
        }else{
           //code为0 说明数据有问题，需要把流程导向失败
           ElMessage.error(res.msg || "接口错误")
           return Promise.reject(res); 
        }
    })

}
